package com.huike.xingxing.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.huike.xingxing.R;
import com.huike.xingxing.api.Api;
import com.huike.xingxing.bean.EverStatus;
import com.huike.xingxing.bean.Notice;
import com.huike.xingxing.ui.CircleImageView;
import com.huike.xingxing.ui.Textmarquee;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.huike.xingxing.bean.Warning;
public class HomeFragment extends BaseFragment {
    Context context;
    private Banner banner;
    private ArrayList<Integer> image;
    private ArrayList<String> title;
    private View view;
    private Banner bn_home;
    private Textmarquee tv_home_title;
    private ListView lv_home_status;
    private ListView lv_home_early;
    private RequestQueue queue;
    private ArrayList<String> bannerList;
    private EverStatus everStatus;
    private Warning warning;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bannerList = new ArrayList<>();
        context = getActivity();
        queue = Volley.newRequestQueue(context);
        image = new ArrayList<>();
        image.add(R.drawable.back);
        image.add(R.drawable.tz);
        image.add(R.drawable.zx0);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = View.inflate(context, R.layout.home_fragmeng, null);
        initView();
        getBannerData(); // TODO 得到轮播图  图片
        initBanner();
        getEverStatus();
        getWringData();
        getNoticeData(); //得到最新公告数据
        return view;
    }


    //得到最新公告数据
    private void getNoticeData() {
        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "getNotice", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Notice notice = new Gson().fromJson(jsonObject.toString(), Notice.class);

                tv_home_title.setText(notice.getData().get(0).getMessages());

            }
        },null);

        queue.add(request);
    }

    //获取每日状态
    private void  getEverStatus(){
        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "getEverStatus", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try{
                    Log.e("---", "onResponse: "+jsonObject.toString() );
                    if(!jsonObject.getString("data").equals("fail")){
                        everStatus = new Gson().fromJson(jsonObject.toString(), EverStatus.class);
                        initAdapterStatus();
                    }
                }catch (Exception e){

                }


            }
        },null);

        queue.add(request);
    }

    private void initAdapterEarly() {
        lv_home_early.setAdapter(new EarlyAdapter());
        setListViewHeightBasedOnChildren(lv_home_early);
    }

    private void initAdapterStatus() {
        lv_home_status.setAdapter(new StatusAdapter());
        setListViewHeightBasedOnChildren(lv_home_status);

    }

    //获取心里预警信息
    public void getWringData(){
        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "getWarning", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                warning = new Gson().fromJson(jsonObject.toString(), Warning.class);
                initAdapterEarly();

            }
        },null);

        queue.add(request);
    }

    // TODO 得到轮播图  图片
    private void getBannerData(){
        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "getBanner", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                com.huike.xingxing.bean.Banner json = new Gson().fromJson(jsonObject.toString(), com.huike.xingxing.bean.Banner.class);

                for (int i = 0; i < json.getData().get(0).size(); i++) {
                    String url = Api.url +json.getData().get(0).get(i);

                    bannerList.add(url);
                    Log.e("---", "banner:aaa "+ url);
                    initBanner();
                }

            }
        },null);

        queue.add(request);
    }

    // TODO lisTView 自适应高度
    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除

        listView.setLayoutParams(params);
    }

    //适配器
    class EarlyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return warning.getData().size();
        }

        @Override
        public Object getItem(int position) {
            return warning.getData().get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.early, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }


            Warning.DataBean bean = warning.getData().get(position);
            holder.iv_home_early_txt.setText(bean.getId()+"家长\n"+bean.getCreated_at());
            Glide.with(context).load(Api.url+bean.getHead_img()).into(holder.iv_home_early_heard);


            return convertView;
        }

        class ViewHolder {
            public View rootView;
            public CircleImageView iv_home_early_heard;
            public TextView iv_home_early_txt;

            public ViewHolder(View rootView) {
                this.rootView = rootView;
                this.iv_home_early_heard = (CircleImageView) rootView.findViewById(R.id.iv_home_early_heard);
                this.iv_home_early_txt = (TextView) rootView.findViewById(R.id.iv_home_early_txt);
            }

        }
    }

    class StatusAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return everStatus.getData().size();
        }

        @Override
        public Object getItem(int position) {
            return everStatus.getData().get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.status, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            EverStatus.DataBean bean = everStatus.getData().get(position);
            Log.e("---",bean.toString());

            if(bean.getFettle().equals("general")){
                holder.iv_home_status_image.setImageResource(R.drawable.yiban);
            }else if(bean.getFettle().equals("happy")){
                holder.iv_home_status_image.setImageResource(R.drawable.kaix);
            }else if(bean.getFettle().equals("unhappy") ){
                holder.iv_home_status_image.setImageResource(R.drawable.bukais);
            }

            holder.iv_home_status_txt.setText(bean.getUname()+"家长\n" + bean.getCreated_at());
            Glide.with(context).load(Api.url+bean.getHead_img()).into(holder.iv_home_status_heard);




            return convertView;
        }

        class ViewHolder {
            public View rootView;
            public CircleImageView iv_home_status_heard;
            public TextView iv_home_status_txt;
            public ImageView iv_home_status_image;

            public ViewHolder(View rootView) {
                this.rootView = rootView;
                this.iv_home_status_heard = (CircleImageView) rootView.findViewById(R.id.iv_home_status_heard);
                this.iv_home_status_txt = (TextView) rootView.findViewById(R.id.iv_home_status_txt);
                this.iv_home_status_image = (ImageView) rootView.findViewById(R.id.iv_home_status_image);
            }

        }
    }

    private void initView() {
        banner = view.findViewById(R.id.bn_home);
        tv_home_title = view.findViewById(R.id.tv_home_title);
        lv_home_status = view.findViewById(R.id.lv_home_status);
        lv_home_early = view.findViewById(R.id.lv_home_early);

    }

    private void initBanner() {
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Log.e("---", "displayImage:aaaaasd "+path );
                Glide.with(context.getApplicationContext()).load(path).into(imageView);
            }
        });
        Log.e("", "initBanner: aaa"+bannerList.size() );
        //设置图片网址或地址的集合
        banner.setImages(bannerList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.CubeOut);
        //设置轮播图的标题集合
//        banner.setBannerTitles(title);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER);
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                //必须最后调用的方法，启动轮播图。
        banner.start();
    }


}
